package com.cxq.boot.Interceptors;

import com.cxq.boot.mapper.UserMapper;
import com.cxq.boot.model.User;
import com.cxq.boot.model.UserExample;
import com.cxq.boot.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private NotificationService notificationService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先判断数据库是否存在该用户
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length != 0) {
            for (Cookie cookie : cookies) {
                //73eb3d44-5769-4ec1-a3a3-01abd2051b35
                if (cookie.getName().equals("token")) {
                    String token = cookie.getValue();
                    //System.out.println("token:" + token);

                    UserExample userExample = new UserExample();
                    //createCriteria() 可以拼接sql
                    userExample.createCriteria()
                            .andTokenEqualTo(token);
                    List<User> users = userMapper.selectByExample(userExample);
                    //User user = userMapper.findByToken(token);//替换上面的方式
                    //System.out.println("user:" + users.get(0));//未登录为角标越界

                    //从数据库查是否有 token 进行登录
                    if (users != null && users.size() != 0) {
                        request.getSession().setAttribute("user", users.get(0));

                        //根据用户Id获取通知数,并将其放入Session中
                        Long unreadCount = notificationService.unreadCount(users.get(0).getId());
                        request.getSession().setAttribute("unreadCount",unreadCount);
                    }
                    break;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
